package com.hongbo.simulation

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.hongbo.idscanner.IDCardInfo
import com.hongbo.idscanner.IdScan.KEY_ID_SCAN_INFO
import com.hongbo.idscanner.IdScan.SCAN_FILTER
import com.hongbo.idscanner.databinding.FragmentIdDialogBinding
import com.hongbo.utils.KeyboardTools
import com.hongbo.utils.Player

/**
 * 填写身份证
 */
class IdInputDialog : BottomSheetDialogFragment() {

    private var _binding: FragmentIdDialogBinding? = null

    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentIdDialogBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.button.setOnClickListener { doResult() }
        binding.editTextNumber.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                doResult()
                true
            }
            false
        }
        binding.editTextNumber.post {
            KeyboardTools.showKeyboard(binding.editTextNumber)
        }
    }

    private fun doResult() {
        var inputStr = binding.editTextNumber.text.toString()
        // 发送广播接收身份输入信息
        if (inputStr.isNotEmpty()) {
            KeyboardTools.hideKeyboard(binding.editTextNumber)
            dismiss()
            sendResult(inputStr)
            Player.playMp3()
        }
    }

    companion object {
        fun newInstance(): IdInputDialog = IdInputDialog()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    /**
     * 发送结果广播
     */
    private fun sendResult(idCard: String) {
        val intent = Intent(SCAN_FILTER)
        intent.putExtra(KEY_ID_SCAN_INFO, IDCardInfo().parseInput(idCard))
        context!!.sendBroadcast(intent)
    }
}